/**
 * Copyright © 2016-2023 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.thingsboard.server.service.security.auth.oauth2;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.CustomerConfig;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.oauth2.OAuth2Registration;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.common.data.security.UserCredentials;
import org.thingsboard.server.common.data.security.model.JwtPair;
import org.thingsboard.server.common.data.security.model.JwtToken;
import org.thingsboard.server.dao.customer.CustomerConfigService;
import org.thingsboard.server.dao.customer.CustomerService;
import org.thingsboard.server.dao.oauth2.OAuth2Service;
import org.thingsboard.server.dao.user.UserService;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.auth.jwt.RefreshTokenRepository;
import org.thingsboard.server.service.security.auth.rest.RestAuthenticationDetails;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.UserPrincipal;
import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.utils.AdvancedEncryption;
import org.thingsboard.server.utils.MapCacheUtil;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.PREV_URI_COOKIE_NAME;

@Slf4j
@Component(value = "oauth2AuthenticationSuccessHandler")
@TbCoreComponent
public class Oauth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private final JwtTokenFactory tokenFactory;
    private final OAuth2ClientMapperProvider oauth2ClientMapperProvider;
    private final OAuth2Service oAuth2Service;
    private final OAuth2AuthorizedClientService oAuth2AuthorizedClientService;
    private final HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository;
    private final SystemSecurityService systemSecurityService;

    @Autowired
    public Oauth2AuthenticationSuccessHandler(final JwtTokenFactory tokenFactory,
                                              final OAuth2ClientMapperProvider oauth2ClientMapperProvider,
                                              final OAuth2Service oAuth2Service,
                                              final OAuth2AuthorizedClientService oAuth2AuthorizedClientService,
                                              final HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository,
                                              final SystemSecurityService systemSecurityService) {
        this.tokenFactory = tokenFactory;
        this.oauth2ClientMapperProvider = oauth2ClientMapperProvider;
        this.oAuth2Service = oAuth2Service;
        this.oAuth2AuthorizedClientService = oAuth2AuthorizedClientService;
        this.httpCookieOAuth2AuthorizationRequestRepository = httpCookieOAuth2AuthorizationRequestRepository;
        this.systemSecurityService = systemSecurityService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        log.info("----------");
        System.out.print(authentication);
        log.info("----------");
        OAuth2AuthorizationRequest authorizationRequest = httpCookieOAuth2AuthorizationRequestRepository.loadAuthorizationRequest(request);
        String callbackUrlScheme = authorizationRequest.getAttribute(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME);
        String baseUrl;
        if (!StringUtils.isEmpty(callbackUrlScheme)) {
            baseUrl = callbackUrlScheme + ":";
        } else {
            baseUrl = this.systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request);
            Optional<Cookie> prevUrlOpt = CookieUtils.getCookie(request, PREV_URI_COOKIE_NAME);
            if (prevUrlOpt.isPresent()) {
                baseUrl += prevUrlOpt.get().getValue();
                CookieUtils.deleteCookie(request, response, PREV_URI_COOKIE_NAME);
            }
        }
        try {
            DefaultOAuth2User user= (DefaultOAuth2User) authentication.getPrincipal();
            OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;
            String username =  token.getPrincipal().getAttribute("username");
            TenantId devOpsId = token.getPrincipal().getAttribute("devOpsId");
            processToken(username, devOpsId, response, request);
//            OAuth2Registration registration = oAuth2Service.findRegistration(UUID.fromString(token.getAuthorizedClientRegistrationId()));
//            OAuth2AuthorizedClient oAuth2AuthorizedClient = oAuth2AuthorizedClientService.loadAuthorizedClient(
//                    token.getAuthorizedClientRegistrationId(),
//                    token.getPrincipal().getName());
//
//            OAuth2ClientMapper mapper = oauth2ClientMapperProvider.getOAuth2ClientMapperByType(registration.getMapperConfig().getType());
//            SecurityUser securityUser = mapper.getOrCreateUserByClientPrincipal(request, token, oAuth2AuthorizedClient.getAccessToken().getTokenValue(),
//                    registration);

            clearAuthenticationAttributes(request, response);
//            JwtPair tokenPair = tokenFactory.createTokenPair(securityUser);
//            getRedirectStrategy().sendRedirect(request, response, getRedirectUrl(baseUrl+"/switchuser", tokenPair));
//            systemSecurityService.logLoginAction(securityUser, new RestAuthenticationDetails(request), ActionType.LOGIN, registration.getName(), null);
        } catch (Exception e) {
            log.debug("Error occurred during processing authentication success result. " +
                    "request [{}], response [{}], authentication [{}]", request, response, authentication, e);
            clearAuthenticationAttributes(request, response);
            String errorPrefix;
            if (!StringUtils.isEmpty(callbackUrlScheme)) {
                errorPrefix = "/?error=";
            } else {
                errorPrefix = "/login?loginError=";
            }
            getRedirectStrategy().sendRedirect(request, response, baseUrl + errorPrefix +
                    URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8.toString()));
        }
    }


    private DecodedJWT parseJWT(String token) {
        try {
            return JWT.decode(token);
        } catch (JWTDecodeException e) {
            throw new RuntimeException("解析token失败" + token, e);
        }
    }

    protected void clearAuthenticationAttributes(HttpServletRequest request, HttpServletResponse response) {
        super.clearAuthenticationAttributes(request);
        httpCookieOAuth2AuthorizationRequestRepository.removeAuthorizationRequestCookies(request, response);
    }

    String getRedirectUrl(String baseUrl, JwtPair tokenPair) {
        if (baseUrl.indexOf("?") > 0) {
            baseUrl += "&";
        } else {
            baseUrl += "?";
        }
        return baseUrl + "accessToken=" + tokenPair.getToken() + "&refreshToken=" + tokenPair.getRefreshToken();
    }

    private String getUsernameFromToken(DecodedJWT decode) {
        String username = decode.getClaim("username").asString();
        username = "sdyz_futianshun";
        log.info("用户名 - " + username);
        return username;
    }
    private TenantId getTenantIdFromUsername(String username) {
        return new TenantId(UUID.nameUUIDFromBytes(username.getBytes()));
    }

    private void processToken(String username, TenantId devOpsId, HttpServletResponse response, HttpServletRequest request) throws Exception {
        List<CustomerConfig> customerConfigList = customerConfigService.findCustomerConfigByUsername(username);

        if (customerConfigList.size() == 1) {
            // 处理单个用户情况
            processSingleUser(customerConfigList.get(0), username, devOpsId, response, request);
        } else if (customerConfigList.size() > 1) {
            // 处理多个用户情况
            processMultipleUsers(customerConfigList, username, response);
        } else {
            log.info("无对应处理中心租户信息:" + username);
            response.sendRedirect(homeUri + "/login/selectUser");
        }
    }
    private void processMultipleUsers(List<CustomerConfig> customerConfigList, String username, HttpServletResponse response) throws Exception {
        customerConfigList.forEach(x -> {
            mapcacheutil.add(x.getLoginUser().concat(x.getOrgUser()), x.getAuthority(), 60000);
        });

//        jwtTokenFactory.createAccessJwtToken();
        response.sendRedirect(homeUri + "/login/selectUser?usertoken=" + AdvancedEncryption.encryptString(username,
                algorithm, key));
    }

    @Autowired
    UserService userService;
    private void processSingleUser(CustomerConfig customerConfig, String username, TenantId devOpsId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String orgUserName = customerConfig.getOrgUser();
        String authority = customerConfig.getAuthority();
        log.info("Org User: " + orgUserName);

        User user = userService.findUserByEmail(devOpsId, orgUserName.concat(defaultEmail));
        if (user == null) {
            log.info("无对应处理中心租户信息:" + username);
            response.sendRedirect(homeUri + "/login/selectUser");
        } else {
            if (authority.equals(Authority.TENANT_ADMIN.name())) {
                log.info("租户已存在 - " + user.toString());
                response.sendRedirect(oauthTokenLogin(user, request, response));
            } else {
                response.sendRedirect(oauthTokenLogin(getOrCreateCustomer(user, username), request, response));
            }
        }
    }

    private String oauthTokenLogin(User saveUser, HttpServletRequest request, HttpServletResponse response) {
        //登录
        JwtToken accessToken;
        JwtToken refreshToken;
        try {
            UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, saveUser.getEmail());
            SecurityUser securityUser = new SecurityUser(saveUser, true, principal);
            accessToken = tokenFactory.createAccessJwtToken(securityUser);
            refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
        } catch (Exception e) {
            log.error("Can't get or create security user from oauth2 user", e);
            throw new RuntimeException("Can't get or create security user from oauth2 user", e);
        }
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(homeUri);
        builder.path("/");
        builder.queryParam("accessToken", accessToken);
        builder.queryParam("refreshToken", refreshToken);
        URI location = builder.build().toUri();
        log.info("重定向 - " + location.toString());
        return homeUri + "/?accessToken=" + accessToken.getToken()
                + "&refreshToken=" + refreshToken.getToken();
    }
    @Autowired
    private RefreshTokenRepository refreshTokenRepository;
    @Value("${security.oauth2.clients.default.homeUri}")
    private String homeUri;
    @Resource
    private MapCacheUtil mapcacheutil;
    @Autowired
    CustomerConfigService customerConfigService;

    private User getOrCreateCustomer(User user, String oldName) {
        //判断处理中心租户是否存在，存在则以devops用户作为登录用户，登录租户下的用户
        User customerUser = new User();
        if (user != null) {
            boolean equals = user.getCustomerId().getId().toString().equals(TenantId.SYS_TENANT_ID.getId().toString());
            CustomerId customerId = user.getCustomerId() != null && !equals ?
                    user.getCustomerId() : getCustomerId(user.getTenantId(), oldName.concat(defaultEmail));
            String customer = oldName.concat("_").concat(user.getEmail());
            customerUser.setEmail(customer);
            customerUser.setCustomerId(customerId);
            customerUser.setAuthority(Authority.CUSTOMER_USER);
            TenantId tenantId = user.getTenantId();
            customerUser.setTenantId(tenantId);
            User loginCustomer = userService.findUserByEmail(tenantId, customer);
            if (loginCustomer == null) {
                customerUser = userService.saveUser(tenantId,customerUser);
                log.info("创建用户 - " + customerUser.toString());
                UserCredentials userCredentials = userService.findUserCredentialsByUserId(customerUser.getTenantId(), customerUser.getId());
                if (userCredentials == null) {
                    userService.activateUserCredentials(customerUser.getTenantId(), userCredentials.getActivateToken(), passwordEncoder.encode(""));
                }
            } else {
                customerUser = loginCustomer;
            }
        }
        return customerUser;
    }
    @Autowired
    CustomerService customerService;
    private CustomerId getCustomerId(TenantId tenantId, String customerName) {
        if (StringUtils.isEmpty(customerName)) {
            return null;
        }
        Optional<Customer> customerOpt = customerService.findCustomerByTenantIdAndTitle(tenantId, customerName);
        if (customerOpt.isPresent()) {
            return customerOpt.get().getId();
        } else {
            Customer customer = new Customer();
            customer.setTenantId(tenantId);
            customer.setTitle(customerName);
            return customerService.saveCustomer(customer).getId();
        }
    }

    @Value("${security.oauth2.clients.default.mapperConfig.basic.defaultEmail}")
    private String defaultEmail;
    @Autowired
    JwtTokenFactory jwtTokenFactory;

    @Value("${security.oauth2.clients.default.mapperConfig.basic.algorithm}")
    private String algorithm;
    @Value("${security.oauth2.clients.default.mapperConfig.basic.algorithmKey}")
    private String key;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

}
